<template>
  <div>
    <div class="search-container">
      <el-input
        style="width: 400px; margin-right: 10px"
        size="large"
        v-model="data.name"
        :placeholder="$t('search.inputPlaceholder')"
        prefix-icon="Search"
        clearable
      >
        <template #prepend>
          <!-- 分类选择框 -->
          <el-select
            v-model="data.select"
            :placeholder="$t('search.categoryPlaceholder')"
            style="width: 100px"
            size="large"
            @change="load"
          >
            <!-- 避免空数组调用filter，确保categories有数据再渲染 -->
            <el-option-group
              v-for="category in (data.categories || []).filter(
                (c) => c.parentId === null
              )"
              :key="category.id"
              :label="category.name"
            >
              <!-- 二级分类选项，过滤出该一级分类的子分类 -->
              <el-option
                v-for="subCategory in (data.categories || []).filter(
                  (c) => c.parentId === category.id
                )"
                :key="subCategory.id"
                :label="subCategory.name"
                :value="subCategory.id"
              />
            </el-option-group>
          </el-select>
        </template>
      </el-input>
      <el-button type="primary" @click="load">{{
        $t("search.buttonText")
      }}</el-button>
    </div>

    <section class="product_list">
      <el-row :gutter="20">
        <el-col
          v-for="product in data.productsList"
          :key="product.id"
          :span="6"
        >
          <el-card
            :body-style="{ padding: '10px' }"
            class="product-card product-card-fixed"
          >
            <img
              :src="getProductImage(product)"
              alt="Product Image"
              class="product-image"
            />
            <h2
              class="product-name"
              :title="product.name"
              @click="goToDetails(product.id)"
            >
              {{ product.name }}
            </h2>
            <div style="margin: 10px 0; display: flex; align-items: center">
              <div style="flex: 1">
                <strong style="color: red; font-size: 18px"
                  >￥{{ product.price }}</strong
                >
              </div>
              <div style="flex: 1">
                {{ $t("products.stock") }}：{{ product.stock }}
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <div class="pagination-container">
        <el-pagination
          @current-change="selectByPage"
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="data.total"
        />
      </div>
    </section>
  </div>
</template>

<script setup>
import "../../assets/css/Products.css";
import { reactive, ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import request from "@/utils/request.js";
import { ElMessage } from "element-plus";
const isAddingToCart = ref(false); // 新增这个响应式数据用于控制按钮加载状态

// 假设之前从localStorage获取用户信息并解析的代码逻辑如下（如果已经在其他地方做了此操作，可直接使用获取到的用户ID）
const userInfo = JSON.parse(localStorage.getItem("xm-pro-user"));
const buyerid = userInfo.id;
console.log("用户ID为：", buyerid);
console.log("用户id类型为：", typeof buyerid);

const router = useRouter();
const isLoading = ref(true);

const data = reactive({
  pageNum: 1,
  pageSize: 10,
  productsList: [],
  name: null,
  select: null, //分类id
  categories: [], //分类数据
  total: 0,
});

//获取分类数据
const loadCategories = () => {
  request
    .get("/Category/selectAll")
    .then((res) => {
      if (res.msg === "成功") {
        data.categories = res.data; // 设置分类数据
      } else {
        ElMessage({
          message: "获取分类数据失败",
          type: "error",
        });
      }
    })
    .catch((err) => {
      console.error("获取分类数据失败", err);
      ElMessage({
        message: "获取分类数据失败，请稍后重试",
        type: "error",
      });
    });
};

//获取商品的第一张图片
const getProductImage = (product) => {
  //如果商品有多张图片，返回第一张图片
  if (product.imagePath && product.imagePath.length > 0) {
    const imageFiles = product.imagePath.split(";");
    return imageFiles.length > 0 ? `${imageFiles[0]}` : ""; // 假设图片数组是 `images`
  }
  return "";
};

//请求数据
const load = () => {
  isLoading.value = true;
  request
    .get(`/Ai/abbreviation`, {
      params: {
        text: data.name,
      },
    })
    .then((res) => {
      if (res.data) {
        console.log("搜索商品数据为：", res);
        data.productsList = res.data;
        data.total = res.data.length;
        console.log("商品总数为：", data.total);
      }
      isLoading.value = false;
    })
    .catch((error) => {
      console.log("请求商品数据失败:", error);
      ElMessage({
        message: "请求商品数据失败，请稍后重试",
        type: "error",
      });
      isLoading.value = false;
    });
};

//请求数据
const selectByPage = () => {
  isLoading.value = true;
  // 调用分页查询接口
  request
    .get(`/product/selectPage`, {
      params: {
        pageNum: data.pageNum,
        pageSize: data.pageSize,
        searchKeyword: data.name,
      },
    })
    .then((res) => {
      if (res.data && res.data.list) {
        console.log("分页查询商品数据为：", res);
        data.productsList = res.data.list;
        data.total = res.data.total;
        console.log("商品总数为：", data.total);
      }
      isLoading.value = false;
    })
    .catch((error) => {
      console.log("请求商品数据失败:", error);
      ElMessage({
        message: "请求商品数据失败，请稍后重试",
        type: "error",
      });
      isLoading.value = false;
    });
};

// 查看上架商品信息
const loadListedProducts = () => {
  isLoading.value = true;
  request
    .get("/product/listedProduct")
    .then((res) => {
      if (res.data) {
        console.log("上架商品数据为：", res);
        data.productsList = res.data;
        data.total = res.data.length;
        console.log("上架商品总数为：", data.total);
      }
      isLoading.value = false;
    })
    .catch((error) => {
      console.log("请求上架商品数据失败:", error);
      ElMessage({
        message: "请求上架商品数据失败，请稍后重试",
        type: "error",
      });
      isLoading.value = false;
    });
};

//查看商品详情
const goToDetails = (id) => {
  try {
    request.get(`/product/selectById/${id}`).then((res) => {
      data.productsList = res.data;
      console.log("商品数据为：", res.data);
    });
    router.push({ name: "productDetails", params: { productId: id } });
  } catch (error) {
    console.error("获取商品详情数据出错：", error);
  }
};

// 加入购物车
const addToCart = (product) => {
  isAddingToCart.value = true; //设置按钮为加载状态
  // 发送 POST 请求，将商品添加到购物车
  request
    .post(`/ShoppingCart/addShoppingCart`, {
      buyerid: buyerid,
      productid: product.id,
    }) // 假设默认数量为1
    .then((res) => {
      if (res.msg === "成功") {
        ElMessage({
          message: "添加成功！",
          type: "success",
          duration: 4000, //提示框显示时长
        });
      } else {
        ElMessage({
          message: "添加失败……",
          duration: 3000,
        });
      }
      isAddingToCart.value = false; //恢复状态
    })
    .catch((error) => {
      console.error(error);
      // 使用Element Plus的警告提示样式，显示黄色的提示框
      ElMessage({
        message: "请求失败，请稍后重试",
        type: "warning",
        duration: 3000,
      });
      isAddingToCart.value = false; //恢复状态
    });
};

// 在组件加载时调用一次 load
onMounted(() => {
  loadCategories();
  // 可以根据需求选择调用 load 或 loadListedProducts
  load();
  loadListedProducts();
});
</script>
